#include <REGX52.H>
#include "I2C.h"

void Send_Start()//发送开始信息
{
	SDA=1;//先初始化，防止数据误发
	SCL=1;
	
	SDA=0;//在SCL=1时，SDA置0，发送开始信息
	SCL=0;
}

void Send_End()//发送终止信息
{
	SDA=0;
	SCL=1;
	SDA=1;//在SCL=1时，SDA置1，发送终止信息
}

void Send_Action(unsigned char m)//发送响应
{
	SCL=0;
	SDA=m;//当m为1时，非应答，m为0时，应答
	SCL=1;
	SCL=0;
}

unsigned char Receive_Action()//接收响应
{
	unsigned char temp=0;
	SDA=1;//先释放SDA
	SCL=0;
	temp=SDA;
	SCL=1;
	SCL=0;
	return temp;//当SDA为1时，非应答，SDA为0时，应答
}

void Send_Data(unsigned char m_data)//发送数据
{
	unsigned char i=0;
	SCL=0;
	for(i=0;i<8;i++)//数据传输时，从高位向低位传递
	{
		SDA=m_data&(0x80>>i);
		SCL=1;
		SCL=0;
	}
}

unsigned char Receive_Date()//接收数据
{
	unsigned char m_date=0;
	unsigned char count=0;
	for(count=0;count<8;count++)
	{
		SDA=1;
		SCL=1;//在时钟信号为高电平时，才能够读取数据
		if(SDA==1)
		{
			m_date=m_date|(0x80>>count);
		}
		SCL=0;
	}
	return m_date;
}

void Send_Message(unsigned char w_address,unsigned char m_data)
{
	unsigned char i;
	Send_Start();//发送起始信号
	Send_Data(0xa0);//发送从机地址(写)
	i=Receive_Action();//接收应答
	Send_Data(w_address);//发送写地址
	i=Receive_Action();//接收应答
	Send_Data(m_data);//发送数据
	i=Receive_Action();//接收应答
	Send_End();//发送结束
	return;
}
unsigned char Receive_Message(unsigned char r_address)//接收数据
{
	unsigned char i;
	unsigned char m_data;
	Send_Start();//发送起始信号
	Send_Data(0xa0);//发送从机地址(写)
	i=Receive_Action();//接收应答
	Send_Data(r_address);//发送读地址
	i=Receive_Action();//接收应答
	Send_Start();//发送起始信号
	Send_Data(0xa1);//发送从机地址（读）
	i=Receive_Action();//接收应答
	
	m_data=Receive_Date();//接收数据
	Send_Action(1);//发送应答
	
	Send_End();//发送结束
	return m_data;
}
